package com.nursinghome.admin.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nursinghome.bean.Order;
import com.nursinghome.bean.OrderVo;
import com.nursinghome.bean.RespBean;
import com.nursinghome.common.service.OrderService;
import com.nursinghome.exception.NurisingHomeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Value("${pageSize}")
    private Integer pageSize;
    //获取到所有的订单
    @GetMapping
    public RespBean selectAll(Integer pageNum, Integer pageSize,  Order order) {
        //如何pageNum为空默认查询第一页
        if (pageNum == null){
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orders = orderService.selectByCondition(order);
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        return RespBean.ok("",orderPageInfo);
    }
    //新增订单
    @PostMapping
    public RespBean insert(@RequestBody OrderVo orderVo) throws NurisingHomeException {
        if (orderService.insert(orderVo)) {
            return RespBean.ok("新增成功");
        }
        return RespBean.error("新增失败");
    }
    //修改订单
    @PutMapping
    public RespBean update(@RequestBody Order order) throws NurisingHomeException {
        if (orderService.update(order)) {
            return RespBean.ok("修改成功");
        }
        return RespBean.error("修改失败");
    }
    //删除订单
    @DeleteMapping("/{id}")
    public RespBean deleteById(@PathVariable("id") String id) throws NurisingHomeException {
        if (orderService.delete(id)) {
            return RespBean.ok("删除成功");
        }
        return RespBean.error("删除失败");
    }
    //回显订单数据
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") String id) throws NurisingHomeException {
        Order order = orderService.selectById(id);
        return RespBean.ok("",order);
    }

    //根据老人id查询当天的所有订单
    @GetMapping("/{eid}")
    public RespBean selectByMid(@PathVariable("eid") Long eid){
        List<Order> orders = orderService.selectByCondition(
                new Order() {{
                    setEid(eid);
                    setDate(DateUtil.date());
                }}
        );
        return RespBean.ok("",orders) ;
    }
}
